package org.wangle.seckill.mq.customer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;

import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.wangle.api.goods.provider.GoodsProvider;
import org.wangle.api.order.pojo.Orders;
import org.wangle.api.order.provider.OrdersProvider;
import org.wangle.api.properties.MQ.SecKillProperties;
import org.wangle.seckill.mq.component.publisher.SecKillDelayPublisher;
import org.wangle.seckill.redis.RLock;
import org.wangle.seckill.utils.RedisUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.UUID;

@Slf4j
//用户抢购到了订单单没有在规定的时间内支付，进入死信队列修改订单状态为0
public class SecKillDeathConsumer {

    private String name;

    @Reference
    private OrdersProvider orderService;

    @Reference
    private GoodsProvider goodsService;


    private RedisTemplate<String, Object> redisTemplate = RedisUtils.getRedisTemplate();


    public SecKillDeathConsumer(String name) {
        this.name = name;
    }

    @RabbitListener(queues = SecKillProperties.secKillDeathQueue,containerFactory = "simpleContainerFactory")
    public void consumerMsg(String  order, Channel channel, Message message){
        Orders orders = JSON.parseObject(order, Orders.class);
        log.info(name+"用户【"+orders.getUserId()+"】订单超时失效或者欲购买订单创建失败");
        String uuid = UUID.randomUUID().toString();
        Integer goodsId = orders.getGoodsId();
        Integer userId = orders.getUserId();
        try {
            Boolean member = redisTemplate.opsForSet().isMember(SecKillProperties.goods_buyer_finished_key + goodsId, userId);
            if(member == null || !member){
                orders.setCreateDate(LocalDateTime.now());
                //修改订单状态
                orders.setState(0);
                orderService.save(orders);
                //添加分布式锁
                RLock.tryLock(SecKillProperties.goods_key+orders.getGoodsId(),uuid);

                //redis缓存中添加库存
                redisTemplate.opsForValue().increment(SecKillProperties.goods_nums_key+orders.getGoodsId());
                redisTemplate.opsForSet().remove(SecKillProperties.goods_buyer_finished_key + goodsId, userId);
                //数据库中添加库存
                goodsService.incrementStock(orders.getGoodsId());
                redisTemplate.opsForSet().add(SecKillProperties.goods_buyer_finished_key + goodsId, userId);
                log.info(name+"用户【"+orders.getUserId()+"】取消订单成功");
            }
            //手动应答
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            log.info("订单-消费者-发生异常：{}", "", e.fillInStackTrace());
            //可以将生成订单的错误原因和当前订单的信息存入数据库中
            try {
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            }catch (Exception es){
                es.printStackTrace();
            }
            e.printStackTrace();
        }finally {
            //解除分布式锁
            RLock.unLock(SecKillProperties.goods_key +orders.getGoodsId(),uuid);
        }
    }

}
